from django.shortcuts import render
from .models import Topic, Entry
import logging
logger = logging.getLogger(__name__)

# Create your views here.
def index(request):
    """学习笔记的主页"""
    return render(request, 'learning_logs/index.html')

def topics(request):
    """显示所有主题"""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

def topic(request, topic_id):
    """显示单个主题及其所有的条目"""
    # 1. 确认主题存在
    try:
        topic = Topic.objects.get(id=topic_id)
        logger.debug(f"成功获取主题: id={topic.id}, text={topic.text}")
    except Topic.DoesNotExist:
        logger.error(f"主题不存在: topic_id={topic_id}")
        return HttpResponseNotFound("主题不存在")
    
    # 2. 直接查询Entry模型验证关联
    entries_direct = Entry.objects.filter(topic=topic)
    logger.debug(f"直接查询Entry结果数: {entries_direct.count()}")
    logger.debug(f"SQL语句: {entries_direct.query}")  # 打印原始SQL
    
    # 3. 检查反向关联查询
    entries_reverse = topic.entry_set.all()
    logger.debug(f"反向关联查询结果数: {entries_reverse.count()}")
    
    entries = entries_reverse.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)